package kafka.springboot ;

import java.util.HashMap ;
import java.util.Map ;

import org.apache.kafka.clients.consumer.ConsumerConfig ;
import org.apache.kafka.common.serialization.StringDeserializer ;
import org.springframework.context.annotation.Bean ;
import org.springframework.context.annotation.Configuration ;
import org.springframework.kafka.annotation.EnableKafka ;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory ;
import org.springframework.kafka.config.KafkaListenerContainerFactory ;
import org.springframework.kafka.core.ConsumerFactory ;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory ;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer ;

/**
 * kafka消息监听配置
 * @author 80002165 @date 2017年6月23日 下午5:33:57
 */
@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    @Bean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<String, String>() ;
        factory.setConsumerFactory(consumerFactory()) ;
        factory.setConcurrency(3) ;
        factory.getContainerProperties().setPollTimeout(3000) ;
        return factory ;
    }
    
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<String, String>(consumerConfigs()) ;
    }
    
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<String, Object>() ;
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092") ;
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false) ;
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100") ;
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000") ;
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class) ;
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class) ;
        return propsMap ;
    }
    
    @Bean
    public ConsumerListener listener(){
        return new ConsumerListener() ;
    }
}
